import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { useUserStore } from '@/store/user/user'
import { Response } from '@/service/modules/common/types'
import cookies from 'js-cookie'
import router from '@/router'
import utils from '@/utils'
// NProgress
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const userStore = useUserStore()
/**
 * @description Log and display errors
 */
const handleError = (res: AxiosResponse<any, any>) => {
  // Print to console
  if (import.meta.env.MODE === 'development') {
    utils.log.capsule('TD-DATA', 'UI')
    utils.log.error(res)
  }
  window.$message.error(res.data.resp_msg)
}
const baseURL =
  import.meta.env.MODE === 'development'
    ? import.meta.env.VITE_APP_DEV_WEB_URL
    : import.meta.env.VITE_APP_PROD_WEB_URL
const baseRequestConfig: AxiosRequestConfig = {
  baseURL: baseURL,
  timeout: 15000
  // transformRequest: (params) => {
  //   if (_.isPlainObject(params)) {
  //     return qs.stringify(params, { arrayFormat: 'repeat' })
  //   } else {
  //     return params
  //   }
  // },
  // paramsSerializer: (params) => {
  //   return qs.stringify(params, { arrayFormat: 'repeat' })
  // }
}

const service = axios.create(baseRequestConfig)

const err = (err: AxiosError): Promise<AxiosError> => {
  NProgress.done()
  if (!err.response) {
    window.$message.error('网络连接异常,请稍后再试!')
  }
  if (err.response?.data) {
    const data: Response<any> = err.response.data as Response<any>
    window.$message.error(data.resp_msg)
  }
  if (err.response?.status === 401) {
    userStore.setToken('')
    userStore.setUserInfo({})
    window.$store.commit('updateUserInfo', {})
    router.push({ path: '/login' })
  }

  return Promise.reject(err)
}

service.interceptors.request.use((config: AxiosRequestConfig<any>) => {
  if (!NProgress.isStarted()) {
    NProgress.start()
  }
  const token = userStore.getToken || ''
  const headers = config.headers ? config.headers : {}
  // 请求头中携带token信息
  headers['x-access-token'] = 'token'
  if (!token) {
    headers['Authorization'] =
      'Basic ' +
      window.btoa(
        import.meta.env.VITE_APP_CLIENT_ID +
          ':' +
          import.meta.env.VITE_APP_CLIENT_SECRET
      )
  } else {
    headers['Authorization'] = `Bearer ${token}`
  }
  if (!headers['Content-Type']) {
    headers['Content-Type'] = 'application/json'
  }
  config.headers = headers
  const language = cookies.get('language')
  if (language) config.headers.language = language
  return config
}, err)

// The response to intercept
service.interceptors.response.use((res: AxiosResponse) => {
  NProgress.done()
  // No code will be processed
  if (res.data === undefined) {
    return res.data
  }
  switch (res.data.resp_code) {
    case 0:
      if (res.data.resp_msg) window.$message.success(res.data.resp_msg)
      return res.data
    default:
      handleError(res)
      return res.data
  }
}, err)

export { service as axios }
